import { NextResponse } from "next/server";
const COS = require('cos-nodejs-sdk-v5');

const cos = new COS({
  SecretId: process.env.TENCENT_SECRET_ID,
  SecretKey: process.env.TENCENT_SECRET_KEY,
});

// export const runtime = "edge";

export async function POST(req: Request) {
  if (!process.env.TENCENT_SECRET_ID || !process.env.TENCENT_SECRET_KEY) {
    return new Response("Missing COS credentials. Please add SecretId and SecretKey to your .env file.", {
      status: 401,
    });
  }

  const file = await req.arrayBuffer();
  const filename = req.headers.get("x-vercel-filename") || "file.txt";
  const contentType = req.headers.get("content-type") || "text/plain";
  const fileType = `.${contentType.split("/")[1]}`;
  const finalName = filename.includes(fileType) ? filename : `${filename}${fileType}`;
  const timestamp = Date.now();
  const uniqueKey = `img/${timestamp}_${finalName}`;

  try {
    const result = await new Promise<any>((resolve, reject) => {
      cos.putObject({
        Bucket: process.env.TENCENT_COS_BUCKET,
        Region: process.env.TENCENT_COS_REGION,
        Key: uniqueKey,
        Body: Buffer.from(file),
        ContentType: contentType,
      }, function(err: Error, data: any) {
        if (err) {
          console.error('COS upload error:', err);
          reject(err);
        } else {
          console.log('COS upload success:', data);
          resolve(data);
        }
      });
    });

    return NextResponse.json({
      url: `${process.env.NEXT_PUBLIC_API_BASE_URL}/api/upload/${uniqueKey}`,
    });
  } catch (error) {
    console.error("Error uploading file:", error);
    return NextResponse.json(
      { error: "Failed to upload file" },
      { status: 500 }
    );
  }
}


